package com.iqiyi.pps.epg.web.webapp.action.channel;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import com.iqiyi.pps.epg.api.model.web.channel.TChannel;
import com.iqiyi.pps.epg.api.model.web.channel.TChannelPage;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.web.utils.InnerApiUtil;
import com.iqiyi.pps.epg.web.utils.Struts2Utils;
import com.iqiyi.pps.epg.web.webapp.action.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: xiongwei
 * Mail: xiongwei@qiyi.com
 * Date: 2014/7/10
 * Time: 17:00
 * Desc:
 */

@Namespace("/channel/channel")
@Scope("prototype")
@Results({@Result(name = BaseAction.RELOAD, location = "channel.action", type = "redirect")})
public class ChannelAction extends BaseAction<TChannel>{
    @Autowired
    private ChannelService channelService;
    private Page<TChannel> page;
    private TChannel entity;
    private Long id;

    @Override
    @Action(value = "list")
    public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }
        TPage tPage = new TPage();
        tPage.setPageNo(page.getPageNo());
        tPage.setPageSize(page.getPageSize());
        tPage.setOrderBy(page.getOrderBy());
        tPage.setOrder(page.getOrder());

        String liveType = Struts2Utils.getParameter("live_type");
        String type = Struts2Utils.getParameter("channel_type");
        String qipuId = Struts2Utils.getParameter("qipu_id");
        String name = Struts2Utils.getParameter("channel_name");
        String startDate = Struts2Utils.getParameter("startDate");
        String endDate = Struts2Utils.getParameter("endDate");
        String isEnable = Struts2Utils.getParameter("is_enable");
        String isMemeberFree = Struts2Utils.getParameter("is_memeber_free");

        TFilter tFilter = new TFilter();
        Map<String, String> params = new HashMap();
        if (StringUtils.isNotBlank(liveType)) {
            params.put("liveType", liveType);
        }
        if (StringUtils.isNotBlank(type)) {
            params.put("type", type);
        }
        if (StringUtils.isNotBlank(qipuId)) {
            params.put("qipuId", qipuId);
        }
        if (StringUtils.isNotBlank(name)) {
            params.put("name", name);
        }
        if (StringUtils.isNotBlank(startDate)) {
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            params.put("endDate", endDate);
        }
        if (StringUtils.isNotBlank(isEnable)) {
            params.put("isEnable", isEnable);
        }
        if (StringUtils.isNotBlank(isMemeberFree)) {
            params.put("isMemeberFree", isMemeberFree);
        }

        params.put("pageNo", tPage.getPageNo() + "");
        params.put("pageSize", tPage.getPageSize() + "");
        tFilter.setFilters(params);

        TChannelPage tChannelPage = channelService.getChanneList(tPage, tFilter);
        page.setPageSize(tChannelPage.getTPage().getPageSize());
        page.setPageNo(tChannelPage.getTPage().getPageNo());
        page.setTotalCount(tChannelPage.getTPage().getTotalCount());
        page.setResult(tChannelPage.getResult());
        return SUCCESS;
    }

    @Override
    @Action(value = "input")
    public String input() throws Exception {

        return SUCCESS;
    }

    @Override
    @Action(value = "save")
    public String save() throws Exception {
        String channelId = Struts2Utils.getParameter("id");
        String url = String.format(InnerApiUtil.BASE_URL, "channel/create");
        if (StringUtils.isNotBlank(channelId)) {
            url = String.format(InnerApiUtil.BASE_URL, "channel/edit");
        }
        String respMsg = "保存失败";

        for (int i = 0; i < 3; i++) {
            HttpClientConnection hcc = new HttpClientConnection(url, HttpClientConnection.POST_METHOD);
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("From", "7dpHGKMy4hAh3DmC");
            headers.put("Sign", "#f93Uc31K24()_@");
            headers.put("Time", "1111");
            Map<String, String> params = new HashMap<String, String>();
            if (StringUtils.isNotBlank(channelId)) {
                params.put("id", channelId);
            }

            params.put("name", Struts2Utils.getParameter("name"));
            params.put("shortName", Struts2Utils.getParameter("shortName"));
            params.put("universalCode", Struts2Utils.getParameter("universalCode"));
            params.put("description", Struts2Utils.getParameter("description"));
            params.put("passportId", Struts2Utils.getParameter("passportId"));
            params.put("ppsBaikeId", Struts2Utils.getParameter("ppsBaikeId"));
            params.put("liveType", Struts2Utils.getParameter("liveType"));
            params.put("type", Struts2Utils.getParameter("type"));
            params.put("logoUrl", Struts2Utils.getParameter("logoUrl"));
            params.put("location", Struts2Utils.getParameter("location"));
            params.put("maxPlaybackPeriod", Struts2Utils.getParameter("maxPlaybackPeriod"));
            params.put("tempName", Struts2Utils.getParameter("tempName"));
            params.put("tempStartTime", Struts2Utils.getParameter("tempStartTime"));
            params.put("tempEndTime", Struts2Utils.getParameter("tempEndTime"));
            params.put("qitanId", Struts2Utils.getParameter("qitanId"));
            params.put("orderBy", Struts2Utils.getParameter("orderBy"));
            params.put("isEnable", Struts2Utils.getParameter("isEnable"));
            params.put("tag", Struts2Utils.getParameter("tag"));
            params.put("isMemeberFree", Struts2Utils.getParameter("isMemeberFree"));
            params.put("paidStartTime", Struts2Utils.getParameter("paidStartTime"));
            params.put("paidEndTime", Struts2Utils.getParameter("paidEndTime"));
            hcc.setReqHeaders(headers);
            hcc.setReqParams(params);
            hcc.setSoTimeout(5000);
            hcc.connect();

            if (hcc.getStatus() == 200) {
                JSONObject result = JSONObject.parseObject(hcc.getBody());
                if (result.getString("code").equals("A00000")) {
                    respMsg = "保存成功";
                }
                break;
            }
        }
        addActionMessage(respMsg);
        return INPUT;
    }

    @Override
    @Action(value = "delete")
    public String delete() throws Exception {
        if (id == null) {
            code = "A00001";
            message = "id为空";
        } else {

            code = "A00000";
            message = "删除成功";
        }
        renderAjaxMessage(code,message);
        return null;

    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            String url = String.format(InnerApiUtil.BASE_URL, "channel/get");
            for (int i = 0; i < 3; i++) {
                HttpClientConnection hcc = new HttpClientConnection(url, HttpClientConnection.POST_METHOD);
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("From", "7dpHGKMy4hAh3DmC");
                headers.put("Sign", "#f93Uc31K24()_@");
                headers.put("Time", "1111");
                Map<String, String> params = new HashMap<String, String>();
                params.put("id", Long.toString(id));
                hcc.setReqHeaders(headers);
                hcc.setReqParams(params);
                hcc.connect();
                logger.info("[BasementApiServiceImpl][payment][status][" + hcc.getStatus() + "]");
                if (hcc.getStatus() == 200) {
                    JSONObject result = JSONObject.parseObject(hcc.getBody());
                    entity = result.getObject("data", TChannel.class);
                    if (entity.getIsMemeberFree() > 0) {
                        entity.setPaidEndTime("");
                        entity.setPaidStartTime("");
                    }
                    if (StringUtils.isBlank(entity.getTempName())) {
                        entity.setTempEndTime("");
                        entity.setTempStartTime("");
                    }
                    break;
                }
            }

        } else {
            entity = new TChannel();
            entity.setLiveType(1);
            entity.setType(1);
            entity.setMaxPlaybackPeriod(7200);
            entity.setIsMemeberFree(1);
            entity.setOrderBy(1);
            entity.setIsEnable(1);
            entity.setTag("200003919_200013119");
        }
    }

    @Override
    public TChannel getModel() {
        return entity;
    }


    public Page<TChannel> getPage() {
        return page;
    }

    public void setPage(Page<TChannel> page) {
        this.page = page;
    }

    public TChannel getEntity() {
        return entity;
    }

    public void setEntity(TChannel entity) {
        this.entity = entity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
